package com.credithc.eagleeye.spring.starter;
import com.credithc.eagleeye.plugins.feign.EagleEyeFeignContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.openfeign.FeignContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2019年10月22日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Configuration
@EnableAspectJAutoProxy
@ConditionalOnClass(name = {"feign.Feign", "org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient", "org.springframework.cloud.openfeign.FeignClient"})
@AutoConfigureAfter(name = {"org.springframework.cloud.openfeign.FeignAutoConfiguration"})
public class EagleEyeFeignAutoConfiguration {
    //@Bean
    //@ConditionalOnClass(name = "org.aspectj.lang.ProceedingJoinPoint")
    //@ConditionalOnMissingBean(EagleEyeFeignClientAspect.class)
    //public EagleEyeFeignClientAspect eagleEyeFeignClientAspect() {
    //    return new EagleEyeFeignClientAspect();
    //}

    @Bean
    EagleEyeFeignContextBeanPostProcessor feignContextBeanPostProcessor(BeanFactory beanFactory) {
        return new EagleEyeFeignContextBeanPostProcessor(beanFactory);
    }
}

/**
 * 重新定义FeignContext
 */
class EagleEyeFeignContextBeanPostProcessor implements BeanPostProcessor {
    private BeanFactory beanFactory;

    public EagleEyeFeignContextBeanPostProcessor(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof FeignContext && !(bean instanceof EagleEyeFeignContext)) {
            return new EagleEyeFeignContext((FeignContext) bean, beanFactory);
        }
        return bean;
    }
}
